class Solution1 {
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        int[][] dp = new int[n + 2][n + 2];
        int ret = Integer.MAX_VALUE;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (j == 1) {
                    dp[i][j] = Math.min(dp[i - 1][j + 1], dp[i - 1][j]) + matrix[i - 1][j - 1];
                } else if (j == n) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + matrix[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i - 1][j + 1]), dp[i - 1][j]) + matrix[i - 1][j - 1];
                }
                if (i == n) {
                    if (j == 1) ret = dp[i][j];
                    ret = Math.min(dp[i][j], ret);
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        int[][] matrix = new int[3][3];
        matrix[0] = new int[]{2,1,3};
        matrix[1] = new int[]{6,5,4};
        matrix[2] = new int[]{7,8,9};
        System.out.println(solution1.minFallingPathSum(matrix));
    }
}